//
//  MBDGroupDetailViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/3/17.
//

import Foundation

import UIKit
import YYText
import SnapKit
import SwiftyJSON
import LGAlertView
import Alamofire
import Kingfisher
import Toast_Swift
import JLRoutes

import RxSwift
import RxCocoa

class MBDGroupDetailViewController: MBDBaseViewController, UITextFieldDelegate {
    
    var tableView: UITableView!
    var rightItem : UIButton!
    var viewModel : MBDGroupDetailViewModel!
    var commentsTextField : UITextField!
    var praiseButton : UIButton!
    var bottomBar : UIView!
    static let bottomBarHeight : CGFloat = 44

    init( viewModel: MBDGroupDetailViewModel!) {
        super.init(nibName: nil, bundle: nil)
        self.viewModel = viewModel
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()        
        self.view.setDynamicBackgroundColor()
        
        self.viewModel.replyButtonClicedBlock = {[weak self] cellModel in
            self?.commentsTextField.placeholder = "回复 ".appending(cellModel.posterRealName ?? "无名氏")
            self?.viewModel!.currentCommentId = cellModel.comments.groupCommentId
            self?.viewModel!.currentCommentUserId = cellModel.comments.userId
            self?.commentsTextField.becomeFirstResponder()
        }
        
        self.viewModel.groupCommentReplyButtonClicedBlock = {[weak self] replyModel in
            self?.commentsTextField.placeholder = "回复 ".appending(replyModel.posterRealName ?? "无名氏")
            self?.viewModel!.currentCommentId = replyModel.reply.groupCommentId
            self?.viewModel!.currentCommentUserId = replyModel.reply.userId

            self?.commentsTextField.becomeFirstResponder()
        }
        
        self.viewModel.praiseCompleteBlock = { [weak self] success in
            self?.refreshUI()
        }
        
        tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(tableView)

        
        bottomBar = UIView()
//        bottomBar.backgroundColor = UIColor(colorHex: 0xF4F4F4)
        bottomBar.setDynamicBackgroundColor()
        self.view.addSubview(bottomBar)
        
        commentsTextField = UITextField()
        commentsTextField.borderStyle = .roundedRect
        commentsTextField.placeholder = "写评论..."
        commentsTextField.font = UIFont.systemFont(ofSize: 14)
        commentsTextField.returnKeyType = .send
        commentsTextField.delegate = self
        bottomBar.addSubview(commentsTextField)
        
        praiseButton = UIButton()
        praiseButton.setTitleColor(.gray, for: .normal)
        praiseButton.setImage(UIImage(named: "ico_gdetail_praise"), for: .normal)
        praiseButton.titleLabel?.font = .systemFont(ofSize: 12)
        praiseButton.addTarget(self, action: #selector(praiseClicked), for: .touchUpInside)
        bottomBar.addSubview(praiseButton)
        
        tableView.snp.makeConstraints { make in
            make.left.equalTo(self.view)
            make.top.equalTo(self.view)
            make.right.equalTo(self.view)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-45)
        }
        
        let window = UIApplication.shared.keyWindow
        let bottomPadding : CGFloat = window?.safeAreaInsets.bottom ?? 0
        let screenHeight = UIScreen.main.bounds.height
        let screenWidth = UIScreen.main.bounds.width
        let originY = screenHeight - bottomPadding - MBDGroupDetailViewController.bottomBarHeight
        bottomBar.frame = CGRect(origin: CGPoint(x: 0, y: originY), size: CGSize(width: screenWidth, height: MBDGroupDetailViewController.bottomBarHeight))
        
        commentsTextField.snp.makeConstraints { make in
            make.left.equalTo(MBDGroupCommentsCellModel.MarginLeftAndRightBackgroundView + MBDGroupCommentsCellModel.avatarMarginLeftToSuperView + MBDGroupCommentsCellModel.avatarWidth + MBDGroupCommentsCellModel.marginLeftAvatarAndPoster)
            make.right.equalToSuperview().offset(-66)
            make.centerY.equalToSuperview()
            make.height.equalToSuperview().offset(-7)
        }
        
        praiseButton.snp.makeConstraints { make in
            make.left.equalTo(commentsTextField.snp.right).offset(8)
            make.right.equalToSuperview().offset(-15)
            make.height.equalToSuperview()
            make.centerY.equalTo(commentsTextField)
        }
        
        tableView.setDynamicBackgroundColor()
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 100
        
        tableView.register(MBDGroupDescCell.self, forCellReuseIdentifier: "MBDGroupDescCell")
        tableView.register(MBDGroupPosterCell.self, forCellReuseIdentifier: "MBDGroupPosterCell")
        tableView.register(MBDGroupCodeCell.self, forCellReuseIdentifier: "MBDGroupCodeCell")
        tableView.register(MBDGroupLogoCell.self, forCellReuseIdentifier: "MBDGroupLogoCell")
        tableView.register(MBDGroupQRCodeCell.self, forCellReuseIdentifier: "MBDGroupQRCodeCell")
        tableView.register(MBDGroupNameCell.self, forCellReuseIdentifier: "MBDGroupNameCell")
        tableView.register(MBDGroupContactsCell.self, forCellReuseIdentifier: "MBDGroupContactsCell")
        tableView.register(MBDGroupCommentsCell.self, forCellReuseIdentifier: "MBDGroupCommentsCell")
        tableView.register(MBDGroupCommentsTitleCell.self, forCellReuseIdentifier: "MBDGroupCommentsTitleCell")
        tableView.register(MBDGroupQRCodeTitleCell.self, forCellReuseIdentifier: "MBDGroupQRCodeTitleCell")
        tableView.register(MBDGroupCommentsReplyCell.self, forCellReuseIdentifier: "MBDGroupCommentsReplyCell")
        
        setupNavigationBar()
                
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: "userLogined"), object: nil)
        
        self.registerForKeyboardNotifications()
    }
    
    private func setupNavigationBar() {
        self.navigationController!.navigationBar.setDynamicNavigationBarBackgroundColor2()

        // 设置右侧按钮
        rightItem = UIButton(frame: CGRect(x: 0, y: 0, width: 45, height: 25))
        rightItem.setImage(UIImage(named: "ico_gpdetail_unlock")?.withRenderingMode(.alwaysTemplate), for: .normal)
        if #available(iOS 13.0, *) {
            rightItem.tintColor = .label
        } else {
            // Fallback on earlier versions
        }
        rightItem.addTarget(self, action: #selector(rightItemPressed), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem)
    }
    
    override func updateColors() {
        super.updateColors()
        
        tableView.setDynamicBackgroundColor()
        bottomBar.setDynamicBackgroundColor()
        setupNavigationBar()
        
        // 遍历并更新 cellModels
        self.viewModel.cellModels = self.viewModel.generateCellModels(groupDetail: self.viewModel.groupDetail)
        
        self.tableView.reloadData()
    }
    
    @objc func praiseClicked() {
        
        self.viewModel.doGroupPraiseUpdateRequest(groupId: self.viewModel.groupDetail!.groupId) { result, err in
            if result == true {
                self.refreshUI()
            } else {
                self.view.makeToast(err?.localizedDescription,position: .center)
            }
        }
        
    }
    
    private func registerForKeyboardNotifications(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc func keyboardWasShown(_ notification : Notification){
    
        let info = notification.userInfo
        let endFrame : CGRect = info?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let interval : CGFloat = info?[UIResponder.keyboardAnimationDurationUserInfoKey] as! CGFloat
        var frame = bottomBar.frame
        frame.origin.y = endFrame.origin.y - MBDGroupDetailViewController.bottomBarHeight
        UIView.animate(withDuration: interval) {
            self.bottomBar.frame = frame
        }

    }
    
    @objc func keyboardWillBeHidden(_ notification : Notification){
    
        let info = notification.userInfo
        let endFrame : CGRect = info?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let interval : CGFloat = info?[UIResponder.keyboardAnimationDurationUserInfoKey] as! CGFloat
        
        let window = UIApplication.shared.keyWindow
        let bottomPadding : CGFloat = window?.safeAreaInsets.bottom ?? 0
                
        var frame = bottomBar.frame
        frame.origin.y = endFrame.origin.y - MBDGroupDetailViewController.bottomBarHeight - bottomPadding
        UIView.animate(withDuration: interval) {
            self.bottomBar.frame = frame
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        //前置判断
        if true == textField.text?.isBlank {
            self.view.makeToast("评论的内容不能为空哦",position: .center)
            return false
        }
        
        if textField.text!.length < 5 {
            self.view.makeToast("多说几个字吧",position: .center)
            return false
        }
        
        // 清空
        self.commentsTextField.resignFirstResponder()
        
        if true == textField.placeholder!.hasPrefix("回复") {
            self.doCommentReplyRequest(text: textField.text!)
        } else {
            self.doCommentRequest(text:textField.text!)
        }
        
        return true
    }
    
    func doCommentRequest(text: String) {
        self.viewModel.doPostCommentsRequest(groupId: self.viewModel.groupDetail!.groupId, commentDetail: text) { result, err in

            //出错
            if nil != err {
                self.view.makeToast(err!.localizedDescription)
            } else {
                //成功后置空
                self.commentsTextField.text = ""
                
                //成功
                self.viewModel.groupDetail = result
                self.viewModel.cellModels = self.viewModel.generateCellModels(groupDetail: result)
                self.tableView.reloadData()
            }
        }
    }
    
    func doCommentReplyRequest(text: String) {
        guard (self.viewModel.currentCommentId != nil) else {
            return
        }
        
        guard (self.viewModel.currentCommentUserId != nil) else {
            return
        }
        
        self.viewModel.doPostCommentReplyRequest(groupId: self.viewModel.groupDetail!.groupId,commentId: self.viewModel.currentCommentId!,userId: self.viewModel.currentCommentUserId, commentDetail: text) { result, err in

            //出错
            if nil != err {
                self.view.makeToast(err!.localizedDescription)
            } else {
                //成功后置空
                self.commentsTextField.text = ""
                
                //成功
                self.viewModel.groupDetail = result
                self.viewModel.cellModels = self.viewModel.generateCellModels(groupDetail: result)
                self.tableView.reloadData()
            }
        }
    }
    
    
    @objc func rightItemPressed(){
        if(!MBDUserCenter.shared.userInfoFetched) {
            self.showDetailViewController(MBDLoginViewController(), sender: nil)
            return
        }
        
        let alert = LGAlertView(title: nil, message: "解锁将消耗10个积分", style: .alert, buttonTitles: ["确认"], cancelButtonTitle: "取消", destructiveButtonTitle: nil, actionHandler: {alert,index, title in
            //解锁
            self.doUnlock()
            
        }, cancelHandler: { alertView in
            
        })
        alert.show()
    }
    
    func refreshUI(){
        viewModel.doDetailRequest(groupId: self.viewModel.groupDetail!.groupId) { error,result in
            //未解锁则展示
            if error != nil {
                self.view.makeToast(error?.localizedDescription)
            } else {
                if let unlock = result!.isUnlock {
                    let locked = Int(unlock)! as NSNumber
                    if Bool(truncating: locked) {
                        self.rightItem.isHidden = true
                    } else {
                        self.rightItem.isHidden = false
                    }
                }
                
                //更新 group detail
                self.viewModel.groupDetail = result
                self.viewModel.cellModels = self.viewModel.generateCellModels(groupDetail: result)
                
                if result!.isLike == true {
                    self.praiseButton.setImage(UIImage(named: "ico_gdetail_praised"), for: .normal)
                } else {
                    self.praiseButton.setImage(UIImage(named: "ico_gdetail_praise"), for: .normal)
                }
                let likeCount = Int(result!.likeCount)! < 1 ? "" : result!.likeCount

                self.praiseButton.setTitle(likeCount, for: .normal)

                self.tableView.reloadData()
            }
            
        }
    }
    
    @objc func loginSuccess(){
        self.refreshUI()
    }
    
    /// 解锁
    private func doUnlock(){
        self.viewModel.doUnLockRequest(groupId: self.viewModel.groupDetail!.groupId) { result,err in
            //出错
            if nil != err {
                self.view.makeToast(err!.localizedDescription)
            } else {
                //成功
                if let unlock = result!.isUnlock {
                    let locked = Int(unlock)! as NSNumber
                    if Bool(truncating: locked) {
                        self.rightItem.isHidden = true
                    } else {
                        self.rightItem.isHidden = false
                    }
                    
                    self.viewModel.groupDetail = result
                    self.viewModel.cellModels = self.viewModel.generateCellModels(groupDetail: result)
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshUI()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
      return .lightContent
    }
    
    deinit {
         NotificationCenter.default.removeObserver(self)
    }
}


extension MBDGroupDetailViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.cellModels?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        if cellModel is MBDGroupLogoCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupLogoCell", for: indexPath)
            let realCell = cell as! MBDGroupLogoCell
            realCell.cellModel = cellModel
            return cell
        } else if cellModel is MBDGroupNameCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupNameCell", for: indexPath)
            let realCell = cell as! MBDGroupNameCell
            realCell.cellModel = cellModel
            return cell
        }  else if cellModel is MBDGroupPosterCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupPosterCell", for: indexPath)
            let realCell = cell as! MBDGroupPosterCell
            realCell.cellModel = cellModel
            return cell
        } else if cellModel is MBDGroupDescCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupDescCell", for: indexPath)
            let realCell = cell as! MBDGroupDescCell
            realCell.cellModel = cellModel
            return cell
        } else if cellModel is MBDGroupContactsCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupContactsCell", for: indexPath)
            let realCell = cell as! MBDGroupContactsCell
            realCell.cellModel = cellModel
            return cell
        } else if cellModel is MBDGroupCommentsCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupCommentsCell", for: indexPath)
            let realCell = cell as! MBDGroupCommentsCell
            
            realCell.cellModel = cellModel
            return cell
        }  else if cellModel is MBDGroupCommentsReplyCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupCommentsReplyCell", for: indexPath)
            let realCell = cell as! MBDGroupCommentsReplyCell
            
            realCell.cellModel = cellModel
            return cell
        } else if cellModel is MBDGroupCommentsTitleCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupCommentsTitleCell", for: indexPath)
            let realCell = cell as! MBDGroupCommentsTitleCell
            realCell.cellModel = cellModel
            return cell
        }
        else if cellModel is MBDGroupQRCodeTitleCellModel {
           let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupQRCodeTitleCell", for: indexPath)
           let realCell = cell as! MBDGroupQRCodeTitleCell
           realCell.cellModel = cellModel
           return cell
       }
        
        else if cellModel is MBDGroupQRCodeCellModel {
           let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupQRCodeCell", for: indexPath)
           let realCell = cell as! MBDGroupQRCodeCell
           realCell.cellModel = cellModel
           return cell
       }
        return UITableViewCell()
    }
}


extension MBDGroupDetailViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.commentsTextField.resignFirstResponder()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels![indexPath.row] as! MBDCommonCellModel

        return cellModel.cellHeight()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.commentsTextField.resignFirstResponder()
    }
}



class MBDGroupCodeCell: UITableViewCell {
    var groupCodeImageView:UIImageView!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.contentView.setDynamicForgroundColor()
        
        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        self.contentView.setDynamicForgroundColor()

        self.initialize()
    }

    func initialize() {
        let posterLabel = YYLabel()
        self.contentView.addSubview(posterLabel)

        let posterAttributeString = NSMutableAttributedString(string: "群二维码：")
        posterAttributeString.yy_font = UIFont.systemFont(ofSize: 14)
        posterAttributeString.yy_color = UIColor(colorHex: 0x333333)
        posterLabel.attributedText = posterAttributeString
        
        groupCodeImageView = UIImageView()
        groupCodeImageView.contentMode = UIView.ContentMode.scaleAspectFit
        groupCodeImageView.image = UIImage(named: "group_code")
        self.contentView.addSubview(groupCodeImageView)

        posterLabel.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.equalTo(15)
        }
        
        groupCodeImageView.snp.makeConstraints { make in
            make.top.equalTo(posterLabel.snp.bottom).offset(10)
            make.centerX.equalTo(self.contentView)
            make.height.equalTo(225)
            make.bottom.equalTo(self.contentView).offset(-15)
        }
    }
}




